package com.jason.www;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ElasticSearchHelper {
    private static final String IP_ADDRESS = "127.0.0.1";
    private static final String CLUSTER_NAME = "my-application";
    private static final Integer TCP_PORT = 9300;

    private static TransportClient client;

    static {
        initES();
    }

    private static void initES(){
        try {
            //这里需要制定集群名，不然会报错NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{3QGslRCASXmIZLb6SAugEA}{192.168.6.112}{192.168.6.112:9300}]
            Settings settings = Settings.builder().put("cluster.name", CLUSTER_NAME)
                    .put("client.transport.sniff", true)//启动嗅探功能，这样只需要指定集群中的某一个节点(不一定是主节点)，然后会加载集群中的其他节点，这样只要程序不停即使此节点宕机仍然可以连接到其他节点。
                    .build();
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName(IP_ADDRESS), TCP_PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static TransportClient getElasticSearchClient(){
        return client;
    }

}
